/**
* Copyright (c) 2016-2100 yunclouds
*/
package com.yunqian.web;

import com.yunqian.common.CurrentUser;
import com.yunqian.constant.RedDotKey;
import com.yunqian.exception.ActionException;
import com.yunqian.jwt.JwtUser;
import com.yunqian.redot.constant.OrderStatus;
import com.yunqian.redot.constant.RefundStatus;
import com.yunqian.redot.domain.SwiftpassPay;
import com.yunqian.redot.domain.Ticket;
import com.yunqian.redot.domain.TicketOrder;
import com.yunqian.redot.domain.dto.TicketOrderDto;
import com.yunqian.redot.service.SwiftpassPayService;
import com.yunqian.redot.service.TicketOrderService;
import com.yunqian.redot.service.TicketService;
import com.yunqian.util.HttpUtil;
import com.yunqian.util.validate.Validator;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.*;


/**
 * Describe: 客户门票订单记录控制器
 *
 * @author zsy
 * 2018-09-29 15:55:07
 */
@Log4j2
 @RestController
 @RequestMapping("/api/ticketOrder")
public class TicketOrderController {

     @Autowired
     private TicketOrderService ticketOrderService;
     @Autowired
     private TicketService ticketService;
     @Autowired
     private SwiftpassPayService swiftpassPayService;

    /**
     * 获取分页
     *
     * @param params
     * @return
     */
    @PostMapping("/pagination")
    public Page<TicketOrder> pagination(@RequestBody Map<String, Object> params, @CurrentUser JwtUser user) {
        params.put("_filter_eq_customerId", user.getId());
        return ticketOrderService.pagination(params);
    }

    /**
     * 购票
     *
     * @param ticketOrder 对象信息
     */
    @PostMapping
    public Map<String,String> save(@RequestBody @Valid TicketOrder ticketOrder, HttpServletRequest request, @CurrentUser JwtUser user) {
        ticketOrder.setCustomerId(user.getId());
        return ticketOrderService.saveOrder(ticketOrder, user.getOpenId(), HttpUtil.getIpAddress(request));
    }

    /**
     * 根据id获取详情
     *
     * @param id 要查询的id
     * @return
     */
    @GetMapping("/{id}")
    public TicketOrderDto detail(@PathVariable("id") Long id) {
        TicketOrder order = ticketOrderService.findStrictOne(id);
        String ticketArrStr = order.getRelateTicketArr();
        List<Ticket> ticketList = new ArrayList<>();
        String[] ticketArr = ticketArrStr.substring(1, ticketArrStr.length() - 1).split(",");
        List<Ticket> list = ticketService.findAllByType();
        for(int i=0; i<ticketArr.length; i++){
            for(Ticket ticket : list){
                if(Long.valueOf(ticketArr[i]).equals(ticket.getId())){
                    ticketList.add(ticket);
                }
            }
        }
        TicketOrderDto dto = new TicketOrderDto();
        dto.setTicketOrder(order);
        dto.setTicketList(ticketList);
        return dto;
    }

    /**
     * 重新支付
     * @param orderId
     * @return
     */
    @GetMapping("/pay/anew/{orderId}")
    public Map<String,String> anewPay(@PathVariable("orderId") Long orderId){
        TicketOrder order = ticketOrderService.getById(orderId);
        Map<String,String> map = new HashMap<>(16);
        SwiftpassPay pay = swiftpassPayService.getByOutTradeNo(order.getOrderNo());
        map.put("timeStamp", pay.getTimeStamp());
        map.put("package", pay.getPrepayId());
        map.put("paySign", pay.getPaySign());
        map.put("orderId", orderId.toString());
        map.put("appId", RedDotKey.APP_ID);
        map.put("signType", "RSA");
        map.put("nonceStr",pay.getNonceStr());
        return map;
    }

    /**
     * 退款申请
     * @param id
     * @param params
     */
    @PostMapping("/pay/refund/apply/{id}")
    public void apply(@PathVariable("id") Long id, @RequestBody Map<String,Object> params){
        synchronized (this){
            TicketOrder order = ticketOrderService.getById(id);
            order.setApplyTime(new Date()); // 申请时间
            order.setRefundReason(params.get("refundReason").toString()); // 退款理由
            if(Validator.equals(order.getStatus(), OrderStatus.SUCCESS.getCode())){
                // 如果是已支付订单则直接退款
                ticketOrderService.refund(order);
            }else if(Validator.equals(order.getStatus(), OrderStatus.HAVE_THE_TICKETS.getCode())){
                // 如果是已取票订单则需要审核
                order.setRefundStatus(RefundStatus.AUDIT.getCode()); // 退款状态 审核中
                ticketOrderService.update(order);
            }else {
                log.warn("退款失败，订单号：" + order.getOrderNo());
                throw new ActionException("退款失败，订单状态异常");
            }
        }
    }

}
